package net.jxvtc.blogv1.service;


import net.jxvtc.blogv1.domain.Comment;
import net.jxvtc.blogv1.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.concurrent.TimeUnit;


@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
	private RedisTemplate redisTemplate;

	//不是  new  ，这里是注入
	@Autowired
	private CommentRepository commentRepository;


	/**
	 * 新增、编辑、保存评论
	 *
	 * @param comment
	 * @return
	 */
	@Override

	public Comment saveOrUpate(Comment comment) {
		Comment comment1 = commentRepository.save(comment);
		// 更新数据后进行缓存更新
		redisTemplate.opsForValue().set("comment_"+comment1.getId(),comment1);
		return comment1;
	}

	/**
	 * 发表评论
	 *
	 * @param comment
	 * @return
	 */

	@Override
	public Comment pubComment(Comment comment) {
		//会根据是否有id，调用insert或update

		Comment comment1 = commentRepository.save(comment);
		redisTemplate.opsForValue().set("comment_"+comment1.getId(),comment1);

		return comment1;
	}



	/**
	 * 删除评论
	 *
	 * @param id
	 */

	@Override
	public void removeComment(Integer id) {

		commentRepository.deleteById(id);
		// 删除数据后进行缓存删除
		redisTemplate.delete("comment_"+id);
	}

	/**
	 * 根据id获取评论
	 *
	 * @param id
	 * @return
	 */

	@Override
	public Comment getCommentById(Integer id) {

// 先从Redis缓存中查询数据
		Object object =  redisTemplate.opsForValue().get("comment_"+id);
		if (object!=null){
			return (Comment)object;
		}else {
			// 缓存中没有，就进入数据库查询
			//加载机制：懒加载
			Optional<Comment> optional = commentRepository.findById(id);
			if(optional.isPresent()){
				Comment comment= optional.get();
				// 将查询结果进行缓存，并设置有效期为1天
				redisTemplate.opsForValue().set("comment_"+id, comment,1, TimeUnit.DAYS);


				return comment;
			}else {
				return null;
			}
		}

	}

	/**
	 * 根据作者名称进行分页模糊查询
	 *
	 * @param author
	 * @param pageable
	 * @return
	 */
	@Override
	public Page<Comment> listCommentsByAuthorLike(String author, Pageable pageable) {
		// 模糊查询
		author = "%" + author + "%";
		Page<Comment> comments = commentRepository.findCommentByAuthorIsLike(
				author, pageable
		);
		return comments;
	}
}
